<?php

namespace App\Http\Controllers\Home;

use App\Helpers\Helpers;
use App\Model\WineProduct;
use App\User;
use EasyWeChat\MiniProgram\Application;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Tymon\JWTAuth\Facades\JWTAuth;

class AuthController extends \App\Http\Controllers\AuthController
{
    protected $middlewareName = "memJWT";

    public function __construct()
    {
        $this->middleware($this->middlewareName, ['except' => ['login','wechatLogin']]);
    }

    public function wechatLogin(Application $app,Request $request)
    {
        $code = $request->input('code');

        if (!$code){
            return $this->failed('not have code');
        }

        $resp = $app->auth->session($code);

        //如果是从分享地址登录，判断为新用户
        $newUser = false;

        if ($resp && isset($resp['openid'])) {

            $openid = $resp['openid'];
            $user = User::findByWeixinId($openid);

            if(!$user) {
                $user = new User();
                $user->weixinId = $openid;
                $newUser = true;
            }

            $user->session_key = $resp['session_key'];
            $user->login_count +=1;
            $user->save();

            $user->updateFromLogin($request,$newUser);

            $token = JWTAuth::fromUser($user);

            return $this->returnLoginSuccess($token,$newUser);
        }
        return $this->failed('登录失败');
    }

    public function me()
    {
        if($user = auth()->user()){
            if (request('userInfo')) {
                $user->updateUserInfoFromWechat(request('userInfo'));//更新保存信息
            }
            $user->can_get_day_coupon = $user->getCanGetDayCouponAttribute();
            return $this->success($user);
        }

        return $this->failed('未登录');
    }

    public function userInfoUpdate(Request $request)
    {
        $user = $this->loginUser();

        if ($user && $request->input('userInfo')) {

            return $this->success($user);
        }
        return $this->failed('fail');
    }

    protected function returnLoginSuccess($token,$isNewUser)
    {
        $data = [
            'access_token' => $token,
            'token_type' => 'bearer',
            'expires_in' => time() + auth()->factory()->getTTL() * 60,
            'isNewUser' => $isNewUser
        ];

        return $this->success($data);
    }
}
